package com.atguigu.flink.window.agg;

import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.util.MyUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2022/11/22
 *
 *     每10s，求所有传感器的vc最大的前三
 *
 */
public class Demo8_Process
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .windowAll(TumblingProcessingTimeWindows.of(Time.seconds(10)))
           .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>()
           {
               @Override
               public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                   // StreamSupport 用来对stream进行计算的工具类
                   List<WaterSensor> top3 = StreamSupport.stream(elements.spliterator(), true)
                                                            .sorted((ws1, ws2) -> -ws1.getVc().compareTo(ws2.getVc()))
                                                            .limit(3)
                                                            .collect(Collectors.toList());

                   out.collect(MyUtil.parseTimeWindow(context.window()) + "===>" + top3.toString());

               }
           })
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class MyAvg{
        private Integer count;
        private Double sum;
    }
}
